<?php
namespace app\spadmin\controller;

use app\common\controller\Backend;
use think\Controller;
use think\Config;
use think\Validate;
use think\captcha\Captcha;
use think\Cache;
use think\Session;
use think\Cookie;
use think\Db;

class Index extends Backend
{
    public function _initialize()
    {
        parent::_initialize();        
    }
    //首页
    public function index()
    {
        
        return $this->fetch();
    }
    public function site(){
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            foreach ($data as $key => $value) {
                Db::name('Config')->where('name',$key)->update(['value'=>$value]);
            }
            
            $this->success('修改成功');
        }
        $config = Db::name('Config')->where('1=1')->select();
        $this->assign('config',$config);
        return $this->view->fetch();
    }
    protected function count($domain=0,$start=null,$end=null){
        if(empty($start) && empty($end)){
            $start = strtotime("-30 days");
            $end = strtotime(date("Y-m-d 23:59:59"));
        }else{
            $start = strtotime($start);
            $end = strtotime($end." 23:59:59");
        }
        $map['create_time'] = ['BETWEEN',[$start,$end]];
        if(!empty($domain)){
            $map['domain_id'] =$domain;
        }
       $sql = Db::name('BrowerLog')->where($map)->field(' DATE(FROM_UNIXTIME(`create_time`)) as `day`, count(`id`) as pv,count( DISTINCT `ip`) as uv ')->group('day')->select();
       $brower = array_column($sql,null,'day');
       $date = [];
       $pv = [];
       $uv = [];
       $sum = [];
       $i = 0;
       while (true) {
            $date[$i] = date('Y-m-d',$i*86400 + $start);
            $pv[$i] = $brower[$date[$i]]['pv']??0;
            $uv[$i] = $brower[$date[$i]]['uv']??0;
            if($pv[$i]>1){
                unset($map['create_time']);
                $map['create_time'] = ['BETWEEN',[strtotime($date[$i]),strtotime($date[$i])+86399]];
               $count = Db::name('BrowerLog')->where($map)->field('ip')->group('ip')->having('count(id)>1')->find();
                $sum[$i] = count($count);
            }else{
                $sum[$i] = $pv[$i];
            }
            if(strtotime($date[$i]) > $end){
                break;
            }else{
                $i++;
            }
       }
       return ['date'=>$date,'pv'=>$pv,'uv'=>$uv,'sum'=>$sum];
    }
    //默认页
    public function dashed(){
        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            $data = $this->request->param();
            $total = $this->count($data['domain']??null,$data['startDate']??null,$data['endDate']??null);
            $this->success('',null,$total);
        }
        $total =$this->count();
        $data['domain'] =  Db::name('Domain')->where('status',1)->count('id');
        $data['user'] = Db::name('User')->where('status',1)->count('id');
        $host = Db::name('Config')->where('name','noneDomian')->value('value');
        $data['host'] = count(\explode("\n",$host));
        $domain = Db::name('Domain')->where('status',1)->select();
        $this->assign('domain',$domain);
        $this->assign('data',$data);
        $this->assign('total',$total);
        return $this->view->fetch();
    }
    public function del(){
        if($this->request->isAjax()){
            $data = $this->request->param();
            if(empty($data['startDate']) || empty($data['endDate'])){
                $this->error('请选择时间范围');
            }
            $start = strtotime($data['startDate']);
            $end = strtotime($data['endDate']." 23:59:59");
            $map['create_time'] = ['BETWEEN',[$start,$end]];
            if(!empty($data['domian'])){
                $map['domain_id'] =$data['domian'];
            }
            Db::name('BrowerLog')->where($map)->delete();
            $this->success('删除成功');
        }
    }
    public function region(){
        if($this->request->isAjax()){
            $data = $this->request->param();
            $map['create_time'] = ['BETWEEN',[strtotime(date('Y-m-d'))-86400,strtotime(date('Y-m-d 23:59:59'))]];
            if(isset($data['domain']) && $data['domain']){
                $map['domain_id'] =  $data['domain'];
            }
            if( isset($data['startDate']) && $data['startDate'] && isset($data['endDate']) && $data['endDate']){
                $map['create_time'] = ['BETWEEN',[strtotime($data['startDate']),strtotime($data['endDate'].' 23:59:59')]];
            }
            $brower = Db::name('BrowerLog')->where($map)->group('region_id')->field('count(`id`) as pv,count(DISTINCT `ip`) as uv,region_id')->select();
            $area = Db::name('Area')->where('pid',0)->field('id,name')->select();
            $data = [];
            $i = 0;
            foreach ($area as $key => $value) {
                $data[$i][$key%2==0?'region1':'region2']=$value['name'];
                $data[$i][$key%2==0?'pv1':'pv2']=0;
                $data[$i][$key%2==0?'uv1':'uv2']=0;
                foreach($brower as $k =>$v){
                    if($v['region_id'] == $value['id']){
                        $data[$i][$key%2==0?'pv1':'pv2']=$v['pv'];
                        $data[$i][$key%2==0?'uv1':'uv2']=$v['uv'];
                    }
                }
                if($key%2 == 1){
                    $i++;
                }
            }
            return $this->result($data);
        }
    }

    public function menu(){
        if($this->request->isAjax()){
            $menu = $this->auth->getMenu();
            foreach ($menu as $key => $value) {
                if($value['type'] != 0){
                    $menu[$key]['href'] = url($value['url']);
                }else{
                    $menu[$key]['href'] = '';
                }
            }
            $this->success('',null,listToTree($menu));
        }
    }

    public function recache(){
        rmdirs(CACHE_PATH, false);
        Cache::clear();
        $this->success('清除缓存成功');
    }

    public function login()
    {
        if($this->request->isPost()){
            $data = $this->request->post('',[],'strip_tags');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                'captcha' => 'require|captcha',
            ];
            $validate = new Validate($rule, [], ['username' => '账户', 'password' => '密码', 'captcha' => '验证码']);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError());
            }
            $result = $this->auth->login($data['username'], $data['password'], $data['keeplogin'] ? 86400*30 : 0);
            if ($result === true) {
                $this->success('登录成功');
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : '账户或者密码错误';
                $this->error($msg);
            }
        }
        if ($this->auth->autologin()) {
            Session::delete("referer");
            $this->redirect('index/index');
        }
        return $this->fetch();
    }

    public function logout()
    {
        if($this->request->isPost()){
            Session::delete("spadmin_admin");
            Cookie::delete("spadmin_keeplogin");
            $this->success('退出成功');
           
        }
    }

    public function captcha() {
        $captcha = new Captcha();
        $captcha->useArithmetic = true;
        return $captcha->entry();
    }
}